package com.js.mail.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.js.mail.product.service.CategoryBrandRelationService;
import com.js.mail.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.js.common.utils.PageUtils;
import com.js.common.utils.Query;

import com.js.mail.product.dao.CategoryDao;
import com.js.mail.product.entity.CategoryEntity;
import com.js.mail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类和子分类,以树形结构组装起来
     *
     * @return java.util.List<com.js.mail.product.entity.CategoryEntity>
     * @author js
     * @date 2021/6/21 23:07
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> list = this.list();
        //找到一级分类
        List<CategoryEntity> level1Menus = list.parallelStream().filter(it -> it.getParentCid() == 0).
                map(menu -> {
                            menu.setChildren(getChildrenMenus(menu, list));
                            return menu;
                        }
                ).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        return level1Menus;
    }

    /**
     * 批量删除
     *
     * @param asList
     * @author js
     * @date 2021/6/27 22:11
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {

        // TODO: 2021/6/27 检查当前删除的菜单是否在其他地方被使用

        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 找到catelog的完整路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        //逆序
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联数据
     *
     * @param category
     */
    @Override
    @Transactional
//    @CacheEvict(value = {"category"}, key = "'getLevel1Categorys'")  //每当修改就删除之前的缓存
    @Caching(evict = {
            @CacheEvict(value = {"category"}, key = "'getLevel1Categorys'"), //每当修改就删除之前的缓存
            @CacheEvict(value = {"category"}, key = "'getCatalogJson'")
    })
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    //需要指定放在哪个名字的缓存[缓存的分区]
    @Cacheable(value = {"category"}, key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Override
    @Cacheable(value = "category", key = "#root.methodName",sync = true)
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        //空结果也缓存,解决缓存穿透问题
        //设置过期时间(加随机值)解决缓存雪崩问题
        //枷锁,:解决缓存击穿

//        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
//        if (StringUtils.isEmpty(catalogJSON)) {
//            //缓存中没有
//            return getCatelogJsonFromDbWithRedisLock();
//        } else {
//            return JSON.parseObject(catalogJSON, new TypeReference<>() {
//            });
//        }
        //查询所有分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();

        Map<String, List<Catelog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查到一级分类的所有二级分类
            List<CategoryEntity> entityList = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catelog2Vo> catelog2Vos = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(entityList)) {
                catelog2Vos = entityList.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找三级分类
                    List<CategoryEntity> entities = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    List<Catelog2Vo.Catelog3Vo> l3List;
                    if (CollectionUtil.isNotEmpty(entities)) {
                        l3List = entities.stream().map(l3 -> new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName())).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(l3List);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //查到的数据转成json放到缓存
        return map;
    }

    /**
     * 分布式锁
     *
     * @return
     */
    private Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        //加锁成功!
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        //得到锁以后去缓存确定,如果没有再继续查询
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            //缓存不为空直接返回
            return JSON.parseObject(catalogJSON, new TypeReference<>() {
            });
        }
        //查询所有分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();

        Map<String, List<Catelog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查到一级分类的所有二级分类
            List<CategoryEntity> entityList = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catelog2Vo> catelog2Vos = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(entityList)) {
                catelog2Vos = entityList.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找三级分类
                    List<CategoryEntity> entities = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    List<Catelog2Vo.Catelog3Vo> l3List;
                    if (CollectionUtil.isNotEmpty(entities)) {
                        l3List = entities.stream().map(l3 -> new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName())).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(l3List);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //查到的数据转成json放到缓存
        String jsonString = JSON.toJSONString(catalogJSON);
        redisTemplate.opsForValue().set("catalogJSON", jsonString);
        return map;
    }


    /**
     * 从数据库查询数据
     *
     * @return
     */
    private Map<String, List<Catelog2Vo>> getCatelogJsonFromDb() {

        synchronized (this) {
            //得到锁以后去缓存确定,如果没有再继续查询
            return getDataFromDb();
        }
    }

    /**
     * 递归收集
     *
     * @param catelogId
     * @param paths
     * @return
     */
    // 225 ,25,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {

        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 根据当前菜单查询子菜单
     *
     * @param root
     * @param categoryEntities
     * @return java.util.List<com.js.mail.product.entity.CategoryEntity>
     * @author js
     * @date 2021/6/21 23:41
     */
    private List<CategoryEntity> getChildrenMenus(CategoryEntity root, List<CategoryEntity> categoryEntities) {
        return categoryEntities.parallelStream().filter(it -> it.getParentCid() == root.getCatId()).map(m -> {
            m.setChildren(getChildrenMenus(m, categoryEntities));
            return m;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).
                collect(Collectors.toList());
    }

}